package com.sergio.compress.cp.mainUtil;

import com.sergio.compress.cp.base.CompressTest;
import com.sergio.compress.cp.base.DecompressResult;
import com.sergio.compress.cp.base.CompressResult;
import com.sergio.compress.cp.base.TestSource;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import org.springframework.util.StopWatch;

import java.util.Date;

import static com.sergio.compress.cp.base.Const.BUFFER_SIZE;

/**
 * @Author : Sergio.D
 * @Description :
 * @CreateDate ：2023/6/14 16:21
 */
public class LZ4 extends CompressTest {
    @Override
    public String getType() {
        return "LZ4";
    }

    public CompressResult compress(byte[] data) {
        //判断byte[]为空
        if (data == null || data.length == 0) {
            return null;
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        LZ4Factory factory = LZ4Factory.fastestInstance();
//        byte[] data = "你好阿尼哦回复哦啊回复奥菲;金丝绒;该色".getBytes("UTF-8");
        final int decompressedLength = data.length;

        LZ4Compressor compressor = factory.fastCompressor();
        int maxCompressedLength = compressor.maxCompressedLength(decompressedLength);
//        byte[] compressed = new byte[maxCompressedLength];
        byte[] compressed = new byte[BUFFER_SIZE];
        int compressedLength = compressor.compress(data, 0, decompressedLength, compressed, 0, maxCompressedLength);
        stopWatch.stop();
        return new CompressResult(getType(), stopWatch.getTotalTimeNanos(), compressed, decompressedLength, compressedLength);
    }

    public DecompressResult decompress(byte[] compressedData, int lengthSource) {
        if (compressedData == null || compressedData.length == 0) {
            return null;
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        LZ4Factory factory = LZ4Factory.fastestInstance();
        LZ4FastDecompressor decompressor = factory.fastDecompressor();
        byte[] restored = new byte[BUFFER_SIZE];
//        byte[] restored = new byte[lengthSource];
        int compressedLength2 = decompressor.decompress(compressedData, 0, restored, 0, lengthSource);
        stopWatch.stop();
        return new DecompressResult(getType(), stopWatch.getTotalTimeNanos(), restored, lengthSource, restored.length);
    }


    @Override
    public CompressResult compress(TestSource testSource) {
        return compress(testSource.getSourceData());
    }

    @Override
    public DecompressResult decompress(CompressResult testSource) {
        return decompress(testSource.getData(), testSource.getLengthSource());
    }
}
